package com.njzxw.fs.commonutil.util;

import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

@Service("requestHelper")
public class RequestHelper {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    
    public String getValue(HttpServletRequest request, String paramName) {
        String obj = request.getParameter(paramName);
        if (obj == null) {
            obj = "";
        }
        return obj.trim();
    }

    public String[] getValues(HttpServletRequest request, String paramName) {
        String[] value;
        value = request.getParameterValues(paramName);
        if (value == null) {
            value = new String[]{};
        }
        return value;
    }

    public String getValuesString(HttpServletRequest request, String paramName) {
        return getValuesString(request, paramName, ",");
    }

    public String getValuesString(HttpServletRequest request, String paramName,
                                  String delims) {
        String temp = "";
        String[] values = request.getParameterValues(paramName);
        if (values == null) {
            return "";
        } else {
            for (int i = 0; i < values.length; i++) {
                if (i == values.length - 1) {
                    temp += values[i].trim();
                } else {
                    temp += values[i].trim() + delims;
                }
            }
        }
        return temp;
    }

    public String getAjaxValue(HttpServletRequest request, String paramName) {
        String obj = request.getParameter(paramName);
        if (obj == null) {
            obj = "";
        }
        try {
            obj = URLDecoder.decode(obj, "UTF-8");
        } catch (Exception e) {
            obj = "";
        }
        obj = obj.replaceAll("<", "&lt;");
        obj = obj.replaceAll(">", "&gt;");
        obj = obj.trim();
        if("undefined".equals(obj)){
            obj = "";
        }
        return obj.trim();
    }

    public int getAjaxIntValue(HttpServletRequest request, String paramName){
        try{
            return Integer.valueOf(getAjaxValue(request, paramName));
        }catch(Exception e){
            return 0;
        }
    }

    public int getAjaxIntValue(HttpServletRequest request, String paramName, int defaut){
        try{
            String val = getAjaxValue(request, paramName);
            if("".equals(val) || val == null){
                return defaut;
            }
            return Integer.valueOf(val);
        }catch(Exception e){
            return defaut;
        }
    }

    public String[] getAjaxValues(HttpServletRequest request, String paramName) {
        String[] value, newValue;
        String tmp = "";
        value = request.getParameterValues(paramName);
        if (value == null) {
            value = new String[]{};
        }
        newValue = value;
        if (value.length > 0) {
            newValue = new String[value.length];
            try {
                for (int i = 0; i < value.length; i++) {
                    tmp = value[i];
                    tmp = URLDecoder.decode(tmp, "UTF-8");
                    tmp = tmp.replaceAll("<", "&lt;");
                    tmp = tmp.replaceAll(">", "&gt;");
                    newValue[i] = tmp;
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return newValue;
    }

    public String getAjaxValuesString(HttpServletRequest request,
            String paramName) {
        return getAjaxValuesString(request, paramName, ",");
    }

    public String getAjaxValuesString(HttpServletRequest request,
            String paramName, String delims) {
        String temp = "";
        String[] values = getAjaxValues(request, paramName);
        if (values == null) {
            return null;
        } else {
            for (int i = 0; i < values.length; i++) {
                if (i == values.length - 1) {
                    temp += values[i].trim();
                } else {
                    temp += values[i].trim() + delims;
                }
            }
        }
        temp = temp.replaceAll("<", "&lt;");
        temp = temp.replaceAll(">", "&gt;");
        return temp;
    }

    /**
     * @description: 获取项目对应的实际路径ַ
     * @author ���� 2012-12-27
     * @param request
     * @return
     */
    public String getRealPath(HttpServletRequest request) {
        return request.getSession().getServletContext().getRealPath("/");
    }

    /**
     * 获取项目地址
     *
     * @return
     */
    public String getWebRootRealPath() {
        String rootPath = this.getClass().getResource("").getPath();
        rootPath = rootPath.substring(0, rootPath.indexOf("WEB-INF") - 1);

        return rootPath;
    }

    /**
     * 获取所有request请求参数key-value
     *
     * @param request
     * @return
     */
    public Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        if (null != request) {
            Set<String> paramsKey = request.getParameterMap().keySet();
            for (String key : paramsKey) {
                params.put(key, getAjaxValue(request, key));
            }
        }
        return params;
    }


    public RequestHelper() {
    }

    /**
     * 获取参数信息
     *
     * @param request
     * @return
     */
    public JSONObject getJsonRequestParams(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader((ServletInputStream) request.getInputStream()));
            String line = null;
            StringBuffer sb = new StringBuffer();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            if(sb.length() == 0){
                return new JSONObject();
            }
            return JSONObject.fromObject(URLDecoder.decode(sb.toString(),"UTF-8"));
        } catch (Exception e) {
            logger.error("获取json参数错误，", e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error("获取json参数关闭资源失败，", e);
                }
            }
        }
        return new JSONObject();
    }

    /**
     * 对签名后的url参数嘻嘻你
     *
     * @param map 待签名授权信息
     *
     * @return
     */
    public String getSign(Map<String, String> map, String rsaKey) {
        List<String> keys = new ArrayList<String>(map.keySet());
        // key排序
        Collections.sort(keys);

        StringBuilder authInfo = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            authInfo.append(buildKeyValue(key, value, false));
            authInfo.append("&");
        }

        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        authInfo.append(buildKeyValue(tailKey, tailValue, false));

        String oriSign = SignUtil.sign(authInfo.toString(), rsaKey);
        String encodedSign = "";

        try {
            encodedSign = URLEncoder.encode(oriSign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return "sign=" + encodedSign;
    }

    /**
     * 拼接键值对 转换成url请求连接 将map转换成如：sasa=1&dsada=2
     *
     * @param map
     * @return
     */
    public String buildParam(Map<String, String> map) {
        List<String> keys = new ArrayList<String>(map.keySet());

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keys.size() - 1; i++) {
            String key = keys.get(i);
            String value = map.get(key);
            sb.append(buildKeyValue(key, value, true));
            sb.append("&");
        }

        String tailKey = keys.get(keys.size() - 1);
        String tailValue = map.get(tailKey);
        sb.append(buildKeyValue(tailKey, tailValue, true));
        return sb.toString();
    }

    /**
     * 拼接键值对 转换成url请求连接
     *
     * @param key
     * @param value
     * @return
     */
    private String buildKeyValue(String key, String value) {
        return this.buildKeyValue(key, value, true);
    }

    /**
     * 拼接键值对 转换成url请求连接
     *
     * @param key
     * @param value
     * @param isEncode
     * @return
     */
    private String buildKeyValue(String key, String value, boolean isEncode) {
        StringBuilder sb = new StringBuilder();
        sb.append(key);
        sb.append("=");
        if (isEncode) {
            try {
                sb.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                sb.append(value);
            }
        } else {
            sb.append(value);
        }
        return sb.toString();
    }

}
